/*
 * @lc app=leetcode.cn id=636 lang=typescript
 *
 * [636] 函数的独占时间
 */

// @lc code=start
function exclusiveTime(n: number, logs: string[]): number[] {
  const ans: number[] = new Array(n).fill(0);
  const stack: number[] = [];

  let preTimestamp = 0;
  for (let log of logs) {
    const [sid, type, stimestamp] = log.split(':');
    let id = Number(sid);
    let timestamp = Number(stimestamp);
    const offset = type === 'end' ? 1 : 0;

    if (stack.length) {
      const idx = stack.length - 1;
      ans[stack[idx]] += timestamp - preTimestamp + offset;
    }

    preTimestamp = timestamp + offset;

    if (type === 'start') {
      stack.push(id);
    } else {
      stack.pop();
    }
  }

  return ans;
}
// @lc code=end
